package com.xyz.rok.tools.service.impl;

import com.xyz.rok.tools.constant.Integral;
import com.xyz.rok.tools.mapper.UserMapper;
import com.xyz.rok.tools.model.User;
import com.xyz.rok.tools.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    @Override
    public User addOrUpdate(User user) {
        User userDb = userMapper.selectByUnionId(user.getUnionId());
        Date now = new Date();
        if (userDb == null) {
            user.setCreateTime(now);
            user.setLastLoginTime(now);
            user.setIntegral(Integral.INIT);
            userMapper.insertSelective(user);
            userDb = new User();
            userDb.setId(user.getId());
            return userDb;
        } else {
            user.setId(userDb.getId());
            user.setUpdateTime(now);
            user.setLastLoginTime(now);
            userMapper.updateByPrimaryKeySelective(user);
            user.setServerId(userDb.getServerId());
            user.setServerCode(userDb.getServerCode());
            user.setPassword(userDb.getPassword());
            return user;
        }

    }
}
